package com.Servlet;

import com.DAO.GradeDao;
import com.Grade;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/updateGrade")
public class UpdateGradeServlet extends HttpServlet {
    private GradeDao gradeDao;

    @Override
    public void init() throws ServletException {
        gradeDao = new GradeDao();
    }

    // POST请求，更新成绩信息
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置字符编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取表单数据
        int id = Integer.parseInt(request.getParameter("id"));
        int studentId = Integer.parseInt(request.getParameter("studentId"));
        String courseName = request.getParameter("courseName");
        double gradeValue = Double.parseDouble(request.getParameter("grade"));

        // 创建更新的成绩对象
        Grade grade = new Grade();
        grade.setId(id);
        grade.setStudentId(studentId);
        grade.setCourseName(courseName);
        grade.setGrade(String.valueOf(gradeValue));

        try {
            // 更新成绩信息
            gradeDao.updateGrade(grade);
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("errorMessage", "更新成绩失败，请稍后重试。");
            request.getRequestDispatcher("editGrade.jsp").forward(request, response);
            return;
        }

        // 重定向到成绩管理页面
        response.sendRedirect("gradeManagement");
    }
}
